package com.summer.utils.email;

import com.summer.utils.commen.JsonCommonResponse;
import com.summer.utils.json_serialization.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 邮件发送
 * @author YuHB
 *
 */
@Repository
public class AlarmSender {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    JsonMapper mapper = JsonMapper.nonEmptyMapper();

    @Value("${email.username}")
    private String username;
    @Value("${email.from}")
    private String from;
    @Value("${email.password}")
    private String password;
    @Value("${email.host}")
    private String host;
    @Value("${MAIL_TRANSPORT_PROTOCOL}")
    private String protocol;

    final Properties props = new Properties();

    /**
     * 发邮件正文+接收人+抄送人
     * @param receivers
     * @param ccs
     * @param title
     * @param content
     * @return
     */
    public JsonCommonResponse sendMail(List<String> receivers, List<String> ccs, String title, String content) {

        try {
            MimeMessage message = getMineMessage(receivers, ccs, title, content);
            // 发送邮件
            Transport.send(message);

        } catch (Exception e) {
            logger.error("--send e-mail appear exc，", e);
            return JsonCommonResponse.failRes("发送邮件，出现错误："+e.getMessage());
        }
        return JsonCommonResponse.succJessRes();
    }

    /**
     * 发邮件 附件+正文+接收人+抄送人
     * @param receivers
     * @param ccs
     * @param title
     * @param content
     * @param file
     * @return
     */
    public JsonCommonResponse sendMailAttachment(List<String> receivers, List<String> ccs, String title, String content, File file) {

        try {
            MimeMessage message = getMineMessage(receivers, ccs, title, content);
            // 发送邮件
            Multipart mp = new MimeMultipart();

            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            FileDataSource fileDataSource = new FileDataSource(file);
            mimeBodyPart.setDataHandler(new DataHandler(fileDataSource));
            mimeBodyPart.setFileName(MimeUtility.encodeText(title+".csv"));
            mp.addBodyPart(mimeBodyPart);

            MimeBodyPart mimeBodyPartContent = new MimeBodyPart();
            mimeBodyPartContent.setContent(content,"text/html;charset=utf-8");
            mp.addBodyPart(mimeBodyPartContent);

            message.setContent(mp);
            message.setSentDate(new Date());
            message.saveChanges();


            Transport.send(message);

        } catch (Exception e) {
            logger.error("--send e-mail appear exc，", e);
            return JsonCommonResponse.failRes("发送邮件，出现错误："+e.getMessage());
        }
        return JsonCommonResponse.succJessRes();
    }


    private MimeMessage getMineMessage(List<String> receivers, List<String> ccs, String title, String content){
        props.put("mail.smtp.auth", "true");//需要身份验证
        props.put("mail.smtp.host", host);//服务器主机名
        props.put("mail.user", from); //发件人地址
        props.put("mail.password", password);//密码
        // 发送邮件协议名称
//        props.setProperty("mail.transport.protocol", protocol);

        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                return new PasswordAuthentication(username, password);
            }
        };
        Session mailSession = Session.getInstance(props, authenticator);
        MimeMessage message = new MimeMessage(mailSession);
        try {
            // 设置发件人
            InternetAddress form = new InternetAddress(
                    props.getProperty("mail.user"));
            message.setFrom(form);
            if (receivers == null || receivers.size() == 0) {
                logger.info("--send e-mail appear exc,没有任何收件人信息，报警信息无法发送……");
                throw new RuntimeException("发送邮件，收件人为空");
            }
            for (String receiver : receivers) {
                // 收件人
                message.addRecipients(Message.RecipientType.TO, receiver);
            }
            if (ccs != null) {
                for (String cc : ccs) {
                    // 抄送
                    message.addRecipients(Message.RecipientType.CC, cc);
                }
            }
            message.setSubject(title);
            message.setContent(content, "text/html;charset=UTF-8");
            // 发送邮件
            return message;
        } catch (RuntimeException e){
            throw new RuntimeException(e.getMessage());

        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("系统异常，e="+e.getMessage());
        }

    }
    
    
}
